package config

import (
	"fmt"
	"github.com/chicken-team-outside/chicken_transmission/client_core/service"
	"github.com/chicken-team-outside/chicken_transmission/model"
	"sync/atomic"
)

var netDiskEnabled atomic.Bool
var netDiskCacheDir atomic.Value
var netDiskDriverInfo atomic.Value

var DefaultNetDiskCacheDir = "/ChickenTransmissionCacheDir"

func initNetDisk() error {
	enabled := false
	err := service.GetOrSaveConfig([]byte("net_disk_driver_enabled"), &enabled)
	if err != nil {
		return fmt.Errorf("failed to get net_disk_driver_enabled: %w", err)
	}
	netDiskEnabled.Store(enabled)

	cacheDir := DefaultNetDiskCacheDir
	err = service.GetOrSaveConfig([]byte("net_disk_cache_dir"), &cacheDir)
	if err != nil {
		return fmt.Errorf("failed to get net_disk_cache_dir: %w", err)
	}
	netDiskCacheDir.Store(cacheDir)

	info := &DriverInfo{
		Vendor: model.Vendor_BaiduNetDisk,
	}
	err = service.GetOrSaveConfig([]byte("net_disk_driver_info"), info)
	if err != nil {
		return fmt.Errorf("failed to get net_disk_driver_info:  %w", err)
	}
	netDiskDriverInfo.Store(info)
	return nil
}

func NetDiskEnabled() bool {
	return netDiskEnabled.Load()
}

func SaveNetDiskEnabled(enabled bool) error {
	err := service.SaveConfigData([]byte("net_disk_driver_enabled"), enabled)
	if err == nil {
		netDiskEnabled.Store(enabled)
	}
	return err
}

func SaveNetDiskCacheDir(cacheDir string) error {
	err := service.SaveConfigData([]byte("net_disk_cache_dir"), cacheDir)
	if err == nil {
		netDiskCacheDir.Store(cacheDir)
	}
	return err
}

func NetDiskCacheDir() string {
	return netDiskCacheDir.Load().(string)
}

func NetDiskDriverInfo() *DriverInfo {
	return netDiskDriverInfo.Load().(*DriverInfo)
}

func SaveNetDiskDriver(info *DriverInfo) error {
	err := service.SaveConfigData([]byte("net_disk_driver_info"), info)
	if err == nil {
		netDiskDriverInfo.Store(info)
	}
	return err
}
